package com.zcsy.manage.service.wxpay.service.impl;


import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.HttpUtil;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.commons.util.WeChatUtils;
import com.zcsy.manage.model.wxpay.WxPayReturnData;
import com.zcsy.manage.model.wxpay.WxPaySendData;
import com.zcsy.manage.service.wxpay.service.IAppWxPayService;
import com.zcsy.manage.service.wxpay.util.TenpayUtil;


@Service
public class AppWxPayServiceImpl implements IAppWxPayService {

    private final static Logger logger = LoggerFactory.getLogger(AppWxPayServiceImpl.class);

    // 微信支付商户开通后 微信会提供appid和appsecret和商户号partner
    private static String appid = "wx1e89883e793e2522";

    private static String appsecret = "2e533df21ffa5c10477a6f8f348ae5af";

    private static String partner = "1377642102";

    // 这个参数partnerkey是在商户后台配置的一个32位的key,微信商户平台-账户设置-安全设置-api安全
    private static String partnerkey = "LPPXIANGJINGWEI12387ZCSYAQWERTYU";

    // 付款发起ip
    private static String spbillCreateIp = "127.0.0.1";

    /**
     * @Description 获取根据传入参数获取预订单号
     * @param orderInfo
     *            订单信息
     * @param orderId
     *            订单号
     * @param totalFee
     *            总价格（单位为分）
     * @return 预订单号
     * @author lipingping 13297986663@163.com
     * @date 2015年11月5日
     */
    public WxPayReturnData buildAdvance(WxPaySendData data) {
        WxPayReturnData returnData = null;

        String trade_type = "APP";

        // 随机字符串
        String nonce_str = getNonceStr();
        data.setTrade_type(trade_type);
        data.setNonce_str(nonce_str);
        data.setMch_id(partner);
        data.setAppid(appid);
        data.setAttach("微信支付");
        data.setSpbill_create_ip(spbillCreateIp);
        // 生成sign签名
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appid);
        parameters.put("mch_id", partner);
        parameters.put("nonce_str", nonce_str);
        parameters.put("body", data.getBody());
        parameters.put("attach", "微信支付");
        parameters.put("out_trade_no", data.getOut_trade_no());

        parameters.put("total_fee", data.getTotal_fee());
        parameters.put("spbill_create_ip", spbillCreateIp);
        parameters.put("notify_url", data.getNotify_url());
        parameters.put("trade_type", trade_type);

        String sign = WeChatUtils.createSign(parameters, partnerkey);
        data.setSign(sign);

        XStream xs = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
        xs.alias("xml", WxPaySendData.class);
        String xml = xs.toXML(data);
        logger.error("统一下单xml为:\n" + xml);

        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

        String returnXml = HttpUtil.getStringFromHttpPost(createOrderURL, xml, "UTF-8");
        logger.error("unifiedOrder:" + returnXml);

        XStream xStream = new XStream(new DomDriver());
        xStream.processAnnotations(WxPayReturnData.class);
        returnData = (WxPayReturnData)xStream.fromXML(returnXml);
        returnData.setMch_secret(partnerkey);

        return returnData;

    }

    /**
     * 获取随机字符串
     * 
     * @return
     */
    public static String getNonceStr() {
        // 随机数
        String currTime = TenpayUtil.getCurrTime();
        // 8位日期
        String strTime = currTime.substring(8, currTime.length());
        // 四位随机数
        String strRandom = TenpayUtil.buildRandom(4) + "";
        // 10位序列号,可以自行调整。
        return strTime + strRandom;
    }
}
